var CartModel = function(data) {
    this.Id = data.Id;
    this.imageUrl = data.imageUrl;
    this.Name = data.Name;
    this.Author = data.Author;
    this.Des = data.Des;
    this.Price = data.Price;
    this.Quantity = data.Quantity ? data.Quantity : 1;
    this.getTotal = function() {
        return parseFloat(this.Price) * parseInt(this.Quantity, 10);
    }
}

var CartListModel = function(data) {
    this.list = new Array();
    for (var i = 0; i < data.length; i++) {
        this.list.push(new CartModel(data[i]));
    }
    this.getTotal = function() {
        var total = 0;
        for (var i = 0; i < this.list.length; i++) {
            total = total + this.list[i].getTotal();
        }
        return total;
    }
}

var CartFunction = {};

CartFunction.SESSION_STORAGE_KEY = 'cartList';

CartFunction.setCartToSessionStorage = function(cartList) {
    sessionStorage.setItem(CartFunction.SESSION_STORAGE_KEY, JSON.stringify(cartList));
}

CartFunction.getCartFromSessionStorage = function() {
    var cartList = null;
    if (sessionStorage.getItem(CartFunction.SESSION_STORAGE_KEY)) {
        cartList = sessionStorage.getItem(CartFunction.SESSION_STORAGE_KEY);
        cartList = JSON.parse(cartList);
    } else {
        cartList = new Array();
    }
    return cartList;
}

CartFunction.clearCartInSession = function() {
    if (sessionStorage.getItem(CartFunction.SESSION_STORAGE_KEY)) {
        sessionStorage.removeItem(CartFunction.SESSION_STORAGE_KEY);
        $id("cart-content").setText("Cart: 0");
    }
}

CartFunction.checkItemInCart = function(model) {
    var cartDetail = new CartModel(model);
    var cartList = CartFunction.getCartFromSessionStorage();
    for(var i = 0; i < cartList.length; i++) {
        if(cartList[i].Id == cartDetail.Id) {
            return true;
        }
    }
    return false;
}

CartFunction.setText = function() {
    var cartList = CartFunction.getCartFromSessionStorage();
    $id("cart-content").setText("Cart: " + cartList.length);
}

CartFunction.addToCart = function (model) {
    try {
        var cartDetail = new CartModel(model);
        var cartList = CartFunction.getCartFromSessionStorage();
        cartList.push(cartDetail);
        CartFunction.setCartToSessionStorage(cartList);
        CartFunction.setText();
        alert("Add to cart successful");
    } catch (ex) {
        alert("Failed when add to cart: " + ex.message);
    }
}

CartFunction.removeFromCart = function(event) {
    try {

        if(confirm("Do you really want to remove this book?")) {
            var model = event.currentTarget.data;
            var cartDetail = new CartModel(model);
            var cartList = CartFunction.getCartFromSessionStorage();
            for (var i = 0; i < cartList.length; i++) {
                if(cartList[i].Id == model.Id) {
                    cartList.splice(i, 1);
                    break;
                }
            }
            CartFunction.setCartToSessionStorage(cartList);
            CartFunction.displayCartList(new CartListModel(cartList));
            CartFunction.setText();
        }
    } catch (ex) {
        alert("Failed when remove: " + ex.message);
    }
}

CartFunction.convertToXML = function(cartList) {
    var result = "";
    result += "<cart>";

    for (var i = 0; i < cartList.list.length; i++) {
        result += "<cart_item>";
        result += "<book>";
        result += "<bookId>";
        result += cartList.list[i].Id;
        result += "</bookId>";
        result += "<bookName>";
        result += cartList.list[i].Name;
        result += "</bookName>";
        result += "<author>";
        result += cartList.list[i].Author;
        result += "</author>";
        result += "<picture>";
        result += cartList.list[i].imageUrl;
        result += "</picture>";
        result += "<price>";
        result += cartList.list[i].Price;
        result += "</price>";
        result += "</book>";
        result += "<quantity>";
        result += cartList.list[i].Quantity;
        result += "</quantity>";
        result += "</cart_item>";
    }

    result += "<order>";
    result += "<orderDate>";
    result += formatDateTime(new Date());
    result += "</orderDate>";
    result += "<paymentMethod>";
    result += $id("cartViewOrderPayment").value;
    result += "</paymentMethod>";
    result += "<receiveAddress>";
    result += $id("cartViewOrderAddress").value;
    result += "</receiveAddress>";
    result += "<receivePhone>";
    result += $id("cartViewOrderPhone").value;
    result += "</receivePhone>";
    result += "<receiverName>";
    result += $id("cartViewOrderName").value;
    result += "</receiverName>";
    result += "<shippingMethod>";
    result += $id("cartViewOrderShipping").value;
    result += "</shippingMethod>";
    result += "</order>";

    result += "<total_price>";
    result += cartList.getTotal();
    result += "</total_price>";

    result += "</cart>";
    return result;
},

CartFunction.convertToJSON = function(cartList) {
    var cartItems = cartList.getElementsByTagName("cart_item");
    var result = new Array();
    var item = null;
    for (var i = 0; i < cartItems.length; i++) {
        item = {};
        item.Id = cartItems[0].getElementsByTagName("book")[0].getElementsByTagName("bookId")[0].childNodes[0].nodeValue;
        item.imageUrl = cartItems[0].getElementsByTagName("book")[0].getElementsByTagName("picture")[0].childNodes[0].nodeValue;
        item.Name = cartItems[0].getElementsByTagName("book")[0].getElementsByTagName("bookName")[0].childNodes[0].nodeValue;
        item.Author = cartItems[0].getElementsByTagName("book")[0].getElementsByTagName("author")[0].childNodes[0].nodeValue;
        item.Price = cartItems[0].getElementsByTagName("book")[0].getElementsByTagName("price")[0].childNodes[0].nodeValue;
        item.Quantity = cartItems[0].getElementsByTagName("book")[0].getElementsByTagName("quantity")[0].childNodes[0].nodeValue;
        result.push(item);
    }
    return result;
},

CartFunction.updateTotal = function() {
    try {
        var cartList = CartFunction.getCartFromSessionStorage();
        for (var i = 0; i < cartList.length; i++) {
            cartList[i].Quantity = $id("cartItemQuantityInput_" + i).value;
        }
        CartFunction.setCartToSessionStorage(cartList);
        CartFunction.displayCartList(new CartListModel(cartList));
    } catch (ex) {
        alert("Error: " + ex.message);
    }
},

CartFunction.checkout = function() {
    if(!confirm("Are you sure about your order?")) {
        return false;
    }

    var url = "http://localhost:8080/book-service/public/cart/checkout";
    var cartList = CartFunction.getCartFromSessionStorage();
    var param = CartFunction.convertToXML(new CartListModel(cartList));

    var callback = {
        success: function(response) {
            hideLoading();
            var cartList = CartFunction.convertToJSON(response);
            CartFunction.displayCartList(new CartListModel(cartList));
            CartFunction.clearCartInSession();
            $id("cartViewSuccess").removeClass("hide");
            $id("cart-container").addClass("hide");
        },
        failure: function(response) {
            hideLoading();
            alert("Error: " + JSON.stringify(response));
        }
    };

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, false);
    xhr.setRequestHeader("Content-Type","application/xml");
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var status = xhr.status;
            if(status == 200) {
                callback.success(xhr.responseXML, xhr);
            } else {
                callback.failure(xhr);
            }
        } else {
            callback.failure(xhr);
        }
    }
    showLoading();
    xhr.send(param);
}

CartFunction.displayCartList = function(model) {
    var list = model.list;
    var rootNode = $id("cartViewList");
    var nodeItemId = "cartItem";

    rootNode.innerHTML = "";
    for(var i = 0; i < list.length;i++) {
        var nodeCart = createDiv();
        nodeCart.id = nodeItemId + i;
        nodeCart.data = list[i];
        nodeCart.position = i;

        var nodeId = createDiv();
        nodeId.id = nodeItemId + "Id_" + i;
        nodeId.addClass("cartViewItem");
        nodeId.addClass("cartViewItemId");
        nodeId.setText(list[i].Id);

        var nodeName = createDiv();
        nodeName.id = nodeItemId + "Name_" + i;
        nodeName.addClass("cartViewItem");
        nodeName.addClass("cartViewItemName");
        nodeName.setText(list[i].Name);

        var nodeAuthor = createDiv();
        nodeAuthor.id = nodeItemId + "Author_" + i;
        nodeAuthor.addClass("cartViewItem");
        nodeAuthor.addClass("cartViewItemAuthor");
        nodeAuthor.setText(list[i].Author);

        var nodeDes = createDiv();
        nodeDes.id = nodeItemId + "Des_" + i;
        nodeDes.addClass("cartViewItem");
        nodeDes.addClass("cartViewItemDes");
        nodeDes.setText(list[i].Des);

        var nodePrice = createDiv();
        nodePrice.id = nodeItemId + "Price_" + i;
        nodePrice.addClass("cartViewItem");
        nodePrice.addClass("cartViewItemPrice");
        nodePrice.setText(list[i].Price);

        var nodeQuantity = createNode("div");
        var nodeQuantityInput = createNode("input");
        nodeQuantityInput.id = nodeItemId + "QuantityInput_" + i;
        nodeQuantityInput.type = "number";
        nodeQuantityInput.min = "1";
        nodeQuantityInput.value = list[i].Quantity;
        nodeQuantity.id = nodeItemId + "Quantity_" + i;
        nodeQuantity.addClass("cartViewItem");
        nodeQuantity.addClass("cartViewItemQuantity");
        nodeQuantity.appendChild(nodeQuantityInput);

        var nodeTotal = createDiv();
        nodeTotal.id = nodeItemId + "Total_" + i;
        nodeTotal.addClass("cartViewItem");
        nodeTotal.addClass("cartViewItemTotal");
        nodeTotal.setText(list[i].getTotal());

        var nodeRemove = createDiv();
        nodeRemove.id = nodeItemId + "Remove_" + i;
        nodeRemove.data = list[i];
        nodeRemove.addClass("cartViewItem");
        nodeRemove.addClass("cartViewItemRemove");
        nodeRemove.setText("X");
        nodeRemove.addEventListener("click", CartFunction.removeFromCart, false);

        nodeCart.appendChild(nodeId);
        nodeCart.appendChild(nodeName);
        nodeCart.appendChild(nodeAuthor);
        nodeCart.appendChild(nodeDes);
        nodeCart.appendChild(nodePrice);
        nodeCart.appendChild(nodeQuantity);
        nodeCart.appendChild(nodeTotal);
        nodeCart.appendChild(nodeRemove);

        rootNode.appendChild(nodeCart);
    }

    $id("cartViewTotalNumber").setText(model.getTotal());
}

CartFunction.openCart = function() {
    var paymentUrl = "http://localhost:8080/book-service/public/cart/payment-method";
    var shippingUrl = "http://localhost:8080/book-service/public/cart/shipping-method";
    var cartList = CartFunction.getCartFromSessionStorage();
    $id("cartViewButtonUpdate").addEventListener("click", CartFunction.updateTotal, false);
    $id("cartViewButtonCheckout").addEventListener("click", CartFunction.checkout, false);
    $id("cartViewSuccess").addClass("hide");
    $id("cart-container").removeClass("hide");
    CartFunction.displayCartList(new CartListModel(cartList));

    ajax.get({
        url: paymentUrl,
        success: function(response) {
            var list = response.getElementsByTagName("payment_method_list");
            $id("cartViewOrderPayment").innerHTML = "";
            for (var i = 0; i < list.length; i++) {
                var option = createNode("option");
                option.value = list[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
                option.text = list[i].getElementsByTagName("method")[0].childNodes[0].nodeValue;
                $id("cartViewOrderPayment").appendChild(option);
            }
        },
        failure: function() {

        }
    })

    ajax.get({
        url: shippingUrl,
        success: function(response) {
            var list = response.getElementsByTagName("shipping_method_list");
            $id("cartViewOrderShipping").innerHTML = "";
            for (var i = 0; i < list.length; i++) {
                var option = createNode("option");
                option.value = list[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
                option.text = list[i].getElementsByTagName("method")[0].childNodes[0].nodeValue;
                $id("cartViewOrderShipping").appendChild(option);
            }
        },
        failure: function() {

        }
    })
}
